<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;

/**
 * Token接口
 */
class Token extends Api
{

    protected $noNeedLogin = ['token', 'device'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 检测Token是否过期
     *
     */
    public function check()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }
    
    /**
     * 检测提交Token是否过期
     */
    public function token(){
        $token = $this->request->post('token');
        $tokenInfo = \app\common\library\Token::get($token);
        if(!$tokenInfo){
            $this->error('授权失效，请重新登录');
        }
        $user = \app\common\model\User::get($tokenInfo['user_id']);
        userLoginLog($tokenInfo['user_id']);
        $this->success('', ['token' => $tokenInfo['token'], 'is_pay' => $user['is_pay']]);
    }
    
    /**
     * 保存设备号
     */
    public function device(){
        $uuid = $this->request->post('uuid');
        $res = model('Device')->where(['uuid'=>$uuid])->find();
        if(empty($res)){
            model('Device')->save(['uuid'=>$uuid, 'createtime'=>time()]);
        }
        $this->success(__('Success'));
    }

    /**
     * 刷新Token
     *
     */
    public function refresh()
    {
        //删除源Token
        $token = $this->auth->getToken();
        \app\common\library\Token::delete($token);
        //创建新Token
        $token = Random::uuid();
        \app\common\library\Token::set($token, $this->auth->id, 2592000);
        $tokenInfo = \app\common\library\Token::get($token);
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

}
